<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/*
 * Admin is Permitted
 *
 * Checks if current uri segments exist in array of uri strings
 *
 * @param string
 * @return bool
 */
if ( ! function_exists('admin_is_permitted'))
{
    function admin_is_permitted($uri)
    {
        $CI =& get_instance();
        $permissions = unserialize($CI->Group_session->permissions);
        $permissions = isset($permissions['access']) ? $permissions['access'] : array();
        $access_options = unserialize(ADMIN_ACCESS_OPTIONS);

        if (( ! in_uri($permissions, $uri) && $CI->Group_session->type == ADMINISTRATOR)  && in_uri($access_options, $uri, TRUE))
        {
            return false;
        }

        return true;
    }   
}
/*set usertype*/
if ( ! function_exists('adminusertype'))
{
	function adminusertype($groupid)
    {
		$CI =& get_instance();
		$user = $CI->session->userdata('admin');
		
		if($user['groupid']==$groupid)
		{
			return true;
		}
		else
		{
			return false;
		}
		
	}
}


/*config data*/
if ( ! function_exists('configdata'))
{
	function configdata()
    {
		$CI =& get_instance();
		$query = & $CI->db->get('setting');
		$config=$query->result_array(); 
		return $config[0];
	}
}

/*pagename*/
if ( ! function_exists('page'))
{
	function page()
    {
		$CI =& get_instance();
		$slug=(string) $CI->uri->segment(1);
		$CI->db->where('slug', $slug);
		$data = & $CI->db->get('pages');		
		$page=$data->result_array();		
		if(!empty($page))
		{
			return $page[0]['slug'];
		}
		else 
		{
			return $slug;
		}
	}
}

/*onlineuser*/
if ( ! function_exists('get_users_online'))
{
	function get_users_online()
    {
		$CI =& get_instance();
		$user = $CI->session->userdata('user');
		
		$onlineuser = array();
        
        $CI->db->select('*');
        $CI->db->from('ci_sessions');
		
		
        $CI->db->where('user_data !=', '');
        //$CI->db->like('user_data', 'user');
        
        $query = $CI->db->get();
		//print_r($query->result());
		
			foreach ($query->result() as $row)
			{
				$udata = unserialize($row->user_data);
				if(isset($udata['user']))
				{
					$time=$row->last_activity +300;
					$timeOut = time(); 
					
					if ($timeOut < $time)
					{ //display name} else
						if($user['userid']!=$udata['user']['userid'])
						{
							$onlineuser[$udata['user']['userid']] = $udata['user']['firstname'];
							/*$CI->db->select('userid,firstname,lastname,photo');
							$CI->db->from('addmate_basic');
							$CI->db->where('userid =', $udata['user']['userid']);
							$onlineuser = $CI->db->get()->result_array();*/
						}
						//$onlineuser[$udata['user']['userid']] = $udata['user']['firstname'];
					}
				}
				/* put data in array using username as key */
				/*if($user['userid']!=$udata['user']['userid'])
				{
					$onlineuser[] = $udata['user']['firstname'];
				}*/
				

			}
			return $onlineuser;
			//print_r($udata);
		
		
	}
}  
// ------------------------------------------------------------------------

/*
 * Set Filter
 *
 * Retrieves the value of a specific filter field from
 * them filter session variable array
 *
 * @param string
 * @param string
 * @return string
 */
if ( ! function_exists('set_filter'))
{
    function set_filter($filter_type, $filter)
    {
        $CI =& get_instance();

        $filter_array = $CI->session->userdata('filter[\'' . $filter_type . '\']');

        if (isset($filter_array[$filter]))
        {
            return $filter_array[$filter];
        }
        else
        {
            return '';
        }
    }
}

// ------------------------------------------------------------------------

/*
 * Process Filter
 *
 * Sets, Gets, and Clears filter session data 
 * for various filters in the admin panel
 *
 * @param string
 * @return array
 */
if ( ! function_exists('process_filter'))
{
    function process_filter($filter_type)
    {
        $CI =& get_instance();

        // Process Filter
        if ($CI->input->post('clear_filter'))
        {
            $CI->session->unset_userdata('filter[\'' . $filter_type . '\']');
            redirect(current_url());
        }
        else
        {
            if ($filter = $CI->input->post('filter'))
            {
                foreach($filter as $key => $value)
                {
                    if ($value == '')
                    {
                        unset($filter[$key]);
                    }
                }

                $CI->session->set_userdata('filter[\'' . $filter_type . '\']', $filter);
                redirect(current_url());
            }
        }

        $filter = ($CI->session->userdata('filter[\'' . $filter_type . '\']')) ? $CI->session->userdata('filter[\'' . $filter_type . '\']') : array();

        return $filter;
    }
}

// ------------------------------------------------------------------------

/*
 * Set Crumbs
 *
 * Generates the html to build the admin panels breadcrumbs 
 *
 * @param array
 * @return string
 */
if ( ! function_exists('set_crumbs'))
{
    function set_crumbs($crumbs)
    {
        if (current_url() == base_url(ADMIN_PATH) || current_url() == base_url(ADMIN_PATH . '/dashboard'))
        {
            $crumb_str = '<span class="first_crumb current">Dashboard</span>';
        }
        else
        {
            $crumb_str = '<a class="first_crumb" href="' . base_url(ADMIN_PATH) . '">Dashboard</a>';
        }

        foreach($crumbs as $uri => $crumb)
        {
            if ($uri == current_url())
            {
                $crumb_str .= '<span class="current">' . $crumb . '</span>';
            }
            else
            {
                $crumb_str .= '<a href="' . base_url(ADMIN_PATH . '/' . trim($uri, '/')) . '">' . $crumb . '</a>';
            }
        }

        return $crumb_str;
    }
}

// ------------------------------------------------------------------------

/*
 * Admin Nav
 *
 * Generates the html to build the admin navigation 
 * showing only links that the admin is permitted
 *
 * @param array
 * @param int
 * @return string
 */
if ( ! function_exists('admin_nav'))
{
    function admin_nav($nav, $depth = 1)
    {
        $list_item = '<ul>';

        foreach($nav as $item)
        {
            $item['url'] = trim($item['url'], '/');

            if (empty($item['hidden']))
            {
                $list_item .= '<li' . (($depth == 1 && is_admin_nav_li_selected($item)) ? ' class="selected"' : '') . ((isset($item['id'])) ? ' id="' . $item['id'] . '"' : '') . '>';
                $list_item .= '<a href="' . site_url(ADMIN_PATH . '/' . $item['url']) . '"' . (($depth == 1) ? ' class="top"' : '') . '>' . $item['title'] . '</a>';

                if ( ! empty($item['sub']))
                {
                    $list_item .= admin_nav($item['sub'], $depth + 1);
                }

                $list_item .= '</li>';
            }
        }

        $list_item .= '</ul>';

        return $list_item;
    }   
}   

// ------------------------------------------------------------------------

/*
 * Show Admin Nav Li
 *
 * Called by admin_nav  to determine is admin is permitted to nav item
 *
 * @param array
 * @param int
 * @return bool
 */
if ( ! function_exists('show_admin_nav_li'))
{
    function show_admin_nav_li($item, $depth = 1)
    {
        if (admin_is_permitted(ADMIN_PATH . '/' . trim($item['url'], '/')) && empty($item['hidden']))
        {
            return TRUE;
        }

        if ( ! empty($item['sub']) && empty($item['hidden']))
        {
            foreach ($item['sub'] as $item)
            {
                if (show_admin_nav_li($item, $depth + 1))
                {
                    return TRUE;
                }
            }
        }

        return FALSE;
    }   
}   

// ------------------------------------------------------------------------

/*
 * Is Admin Nav Li Selected
 *
 * Called by admin_nav to determine if current page 
 * is in the current trail of current nav item
 *
 * @param array
 * @param int
 * @return bool
 */
if ( ! function_exists('is_admin_nav_li_selected'))
{
    function is_admin_nav_li_selected($item, $depth = 1)
    {
        $CI =& get_instance();

        $uri_segments = explode('/', $item['url']);
        $segment_match = TRUE;

        $i = 2;
        foreach($uri_segments as $segment)
        {
            if ($CI->uri->segment($i) != $segment)
            {
                $segment_match = FALSE;
                break;
            }

            $i++;
        }

        if ($segment_match)
        {
            return TRUE;
        }

        if ( ! empty($item['sub']))
        {
            foreach ($item['sub'] as $item)
            {
                if (is_admin_nav_li_selected($item, $depth + 1))
                {
                    return TRUE;
                }
            }
        }

        return FALSE;
    }   
}
if ( ! function_exists('list_admin_nav'))
{  
	function list_admin_nav($list, $depth = 1)
    {
		
        if ($depth == 1)
        {
            $nav = '<ol class="sortable">';
        }
        else
        {
            $nav = '<ol>';
        }

        foreach($list as $Item)
        {
            $nav .= '<li id="list_' . $Item['id'] . '">';

            $nav .= '<div><span class="sortable_handle"></span>' . $Item['title']  . '<span style="float: right;">[ <a href="' . base_url(ADMIN_PATH . "/menu/edititems/".$Item['menu_id']."/".$Item['id']) . '">Edit</a> ] [ <a class="delete" href="' . base_url(ADMIN_PATH . "/menu/deleteitems/".$Item['menu_id']."/".$Item['id']) . '">Delete</a> ]</span></div>';
			
            if ( ! empty($Item['sub']))
            {
                $nav .= list_admin_nav($Item['sub'], $depth + 1);
            }

            $nav .= '</li>';
        }

        $nav .= '</ol>';

        return $nav;
    }
}
if ( ! function_exists('get_nested'))
{
	function get_nested ($treelist)
	{
		
		$array = array();
		foreach ($treelist as $tree) {
			
			if (! $tree['parent_id']) {
				// This page has no parent
				$array[$tree['id']] = $tree;
			}
			else {
				
				// This is a child page
				$array[$tree['parent_id']]['sub'][]= $tree;
				
				//$this->get_nested($tree);
			}
		}
		return $array;
	}
}
if ( ! function_exists('cms_page_menu'))
{  
	function cms_page_menu($list,$ulcalss="", $depth = 1)
    {
		
        if ($depth == 1)
        {
            $nav = '<ul class='.$ulcalss.'>';
        }
        else
        {
            $nav = '<ul>';
        }

        foreach($list as $Item)
        {
            $nav .= '<li>';

            $nav .= '<a href="' . base_url( "/".$Item['slug']) . '">'.$Item['title'].'</a>';
			
            if ( ! empty($Item['sub']))
            {
                $nav .= cms_page_menu($Item['sub'], $depth + 1);
            }

            $nav .= '</li>';
        }

        $nav .= '</ul>';

        return $nav;
    }
}
if ( ! function_exists('cms_page_bmenu'))
{  
	function cms_page_bmenu($list,$liclass="",$ulclass="", $depth = 1)
    {
		//print_r($list);
        $nav="";

        foreach($list as $Item)
        {
            $nav .= '<li class="'.$liclass.'">';
            $nav .= '<a href="' . base_url( "/".$Item['slug']) . '" class="'.$Item['class'].'">'.$Item['title'].'</a>';
		    $nav .= '</li>';
        }

        

        return $nav;
    }
}
function blog_link($blog){
	return 'article/' . intval($blog['postid']) . '/' . e($blog['slug']);
}
function blog_links($blogs){
	$string = '<ul>';
	foreach ($blogs as $blog) {
		$url = blog_link($blog);
		$string .= '<li>';
		$string .= '<h3>' . anchor($url, e($blog->title)) .  ' ›</h3>';
		$string .= '<p class="pubdate">' . e($blog->pubdate) . '</p>';
		$string .= '</li>';
	}
	$string .= '</ul>';
	return $string;
}

if ( ! function_exists('get_excerpt'))
{  
	function get_excerpt($blog, $numwords = 50){
		$string = '';
		$url = blog_link($blog);
		$string .= '<h3>' . anchor($url, e($blog['title'])) .  '</h3>';
		$string .= '<p class="pubdate">' . e($blog['date_added']) . '</p>';
		$string .= '<p>' . e(limit_to_numwords(strip_tags($blog['content']), $numwords)) . '</p>';
		$string .= '<p>' . anchor($url, 'Read more ›', array('title' => e($blog['title']))) . '</p>';
		return $string;
	}
}
function limit_to_numwords($string, $numwords){
	$excerpt = explode(' ', $string, $numwords + 1);
	if (count($excerpt) >= $numwords) {
		array_pop($excerpt);
	}
	$excerpt = implode(' ', $excerpt);
	return $excerpt;
}

function e($string){
	return htmlentities($string);
}
if ( ! function_exists('glob_recursive'))
{
    // Does not support flag GLOB_BRACE
    
    function glob_recursive($pattern, $flags = 0)
    {
        $files = glob($pattern, $flags);
        print_r($files);
        foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir)
        {
            $files = array_merge($files, glob_recursive($dir.'/'.basename($pattern), $flags));
        }
        
        return $files;
    }
}
/*
 * Is Ajax
 *
 * Returns true if request is ajax protocol
 *
 * @return bool
 */
if ( ! function_exists('is_ajax'))
{
    function is_ajax() 
    {
        return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'));
    }
}

/*
 * URL Base64 Encode
 * 
 * Encodes a string as base64, and sanitizes it for use in a CI URI.
 * 
 * @param string
 * @return string
 */
if ( ! function_exists('url_base64_encode'))
{
    function url_base64_encode(&$str="")
    {
        return strtr(
            base64_encode($str),
            array(
                '+' => '.',
                '=' => '-',
                '/' => '~'
            )
        );
    }
}

// ------------------------------------------------------------------------

/*
 * URL Base64 Decode
 *
 * Decodes a base64 string that was encoded by ci_base64_encode.
 * 
 * @param string
 * @return string
 */
if ( ! function_exists('url_base64_decode'))
{
    function url_base64_decode(&$str="")
    {
        return base64_decode(strtr(
            $str, 
            array(
                '.' => '+',
                '-' => '=',
                '~' => '/'
            )
        ));
    }
}